<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商铺编号" prop="shopsCode">
        <HouseInput v-model="queryParams.shopsCode" type="house"/>
      </el-form-item>
      <el-form-item label="收费项目" prop="chargeItemId">
        <el-select v-model="queryParams.chargeItemId" placeholder="请选择收费项目" clearable>
          <el-option
            v-for="dict in chargeitemList"
            :key="dict.id"
            :label="dict.name"
            :value="parseInt(dict.id)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="截止时间" prop="endTime">
        <el-date-picker clearable
                        v-model="queryParams.endTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择费用结束时间">
        </el-date-picker>
      </el-form-item>

<!--      <el-form-item label="缴费时间" prop="startTime">-->
<!--        <el-date-picker clearable-->
<!--                        v-model="queryParams.startTime"-->
<!--                        type="date"-->
<!--                        value-format="yyyy-MM-dd"-->
<!--                        placeholder="请选择缴费时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['zxwy:chargedata:add']"
        >新增
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdds"-->
<!--          v-hasPermi="['zxwy:chargedata:add']"-->
<!--        >批量新增-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chargedataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="id"/>
      <el-table-column label="编号" align="center" prop="shopsCode"/>
      <el-table-column label="收费项目" align="center" prop="chargeItemName"/>
      <el-table-column label="单价" align="center" prop="univalence"/>
      <el-table-column label="费用开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="费用结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="催缴期限" align="center" prop="deadlineTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deadlineTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上次读数" align="center" prop="lastData"/>
      <el-table-column label="本次读数" align="center" prop="thisData"/>
      <el-table-column label="倍率" align="center" prop="rate"/>
      <el-table-column label="损耗" align="center" prop="wastage"/>
      <el-table-column label="数量" align="center" prop="number"/>
      <el-table-column label="金额" align="center" prop="money"/>
<!--      <el-table-column label="实收金额" align="center" prop="fundsReceived"/>-->
<!--      <el-table-column label="付款状态" align="center" prop="paymentState">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.fukuan_status" :value="scope.row.paymentState"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="退款状态" align="center" prop="refundStatus">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.tuikuan_status" :value="scope.row.refundStatus"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="退款总金额" align="center" prop="totalRefundAmount" width="180"/>-->
<!--      <el-table-column label="缴费单号" align="center" prop="billNumber"/>-->
<!--      <el-table-column label="缴费时间" align="center" prop="chargeTime">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.chargeTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="缴费方式" align="center" prop="paymentMethodName">-->
<!--      </el-table-column>-->
<!--      <el-table-column label="收款人" align="center" prop="chargeUser"/>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['zxwy:chargedata:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['zxwy:chargedata:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收费数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编号" prop="shopsId">
          <el-select v-model="form.shopsId" placeholder="商铺完整编号">
            <el-option
              v-for="dict in shopsList"
              :key="dict.id"
              :label="dict.code"
              :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收费项目" prop="chargeItemId">
          <el-select v-model="form.chargeItemId" placeholder="请选择收费项目" clearable>
            <el-option
              v-for="dict in chargeitemList"
              :key="dict.id"
              :label="dict.name"
              :value="parseInt(dict.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单价" prop="univalence">
          <el-input v-model="form.univalence" placeholder="请输入单价"/>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="form.startTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择费用开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
                          v-model="form.endTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择费用结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="缴费期限" prop="deadlineTime">
          <el-date-picker clearable
                          v-model="form.deadlineTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择缴费期限">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上次读数" prop="lastData">
          <el-input v-model="form.lastData" placeholder="请输入上次读数"/>
        </el-form-item>
        <el-form-item label="本次读数" prop="thisData">
          <el-input v-model="form.thisData" placeholder="请输入本次读数"/>
        </el-form-item>
        <el-form-item label="倍率" prop="rate">
          <el-input v-model="form.rate" placeholder="请输入倍率"/>
        </el-form-item>
        <el-form-item label="损耗" prop="wastage">
          <el-input v-model="form.wastage" placeholder="请输入损耗"/>
        </el-form-item>
        <el-form-item label="数量" prop="number">
          <el-input v-model="form.number" placeholder="请输入数量"/>
        </el-form-item>
        <!--        <el-form-item label="滞纳金" prop="latefee">-->
        <!--          <el-input v-model="form.latefee" placeholder="请输入滞纳金" />-->
        <!--        </el-form-item>-->
        <el-form-item label="金额" prop="money">
          <el-input v-model="form.money" :disabled="true" placeholder="请输入金额"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 批量添加收费数据对话框 -->
    <el-dialog :title="title" :visible.sync="open2" width="500px" append-to-body @close="cancel">
      <el-steps :active="active" finish-status="success">
        <el-step title="新增规则"></el-step>
        <el-step title="数据确认"></el-step>
      </el-steps>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div v-if="active===1">
          <el-form-item label="编号" prop="shopsId">
            <el-select v-model="form.shopsId" placeholder="商铺完整编号">
              <el-option
                v-for="dict in shopsList"
                :key="dict.id"
                :label="dict.code"
                :value="parseInt(dict.id)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="收费项目" prop="chargeItemId">
            <el-select v-model="form.chargeItemId" placeholder="请选择收费项目" clearable>
              <el-option
                v-for="dict in chargeitemList"
                :key="dict.id"
                :label="dict.name"
                :value="parseInt(dict.id)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="单价" prop="univalence">
            <el-input v-model="form.univalence" placeholder="请输入单价"/>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker clearable
                            v-model="form.startTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择费用开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker clearable
                            v-model="form.endTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择费用结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="缴费限期" prop="deadlineTime">
            <el-date-picker clearable
                            v-model="form.deadlineTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="请选择缴费期限">
            </el-date-picker>
          </el-form-item>
        </div>
        <div v-if="active===2">
          <el-table v-loading="loading" :data="chargedataList" @selection-change="handleSelectionChange">
            <!--              <el-table-column type="selection" width="55" align="center"/>-->
            <el-table-column label="序号" align="center" prop="id"/>
            <el-table-column label="编号" align="center" prop="shopsCode"/>
            <el-table-column label="收费项目" align="center" prop="chargeItemName"/>
            <el-table-column label="数量" align="center" prop="number"/>
            <el-table-column label="单价" align="center" prop="univalence"/>
            <el-table-column label="金额" align="center" prop="money"/>
            <el-table-column label="费用开始时间" align="center" prop="startTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="费用结束时间" align="center" prop="endTime" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="next">下一步</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addChargedata,
  delChargedata,
  getChargedata,
  listChargedata,
  listChargedataByCode,
  updateChargedata
} from "@/api/zxwy/chargedata";
import {listShops} from "@/api/system/shops";
import {listChargeitem} from "@/api/hyj/chargeitem";
import {listPaymentmethod} from "@/api/msr/paymentmethod";

export default {
  name: "Chargedata",
  dicts: ['sys_job_status', 'sys_user_sex', 'tuikuan_status', 'fukuan_status'],
  data() {
    return {
      active: 1,
      chargeitemList: [],
      paymentmethodList: [],
      //
      shopsList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 收费数据表格数据
      chargedataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        shopsId: null,
        shopsCode: null,
        chargeItemName: null,
        paymentMethodName:null,
        chargeItemId: null,
        startTime: null,
        endTime: null,
        paymentState: null,
        billNumber: null,
        chargeTime: null,
      },
      // 表单参数
      form: {
        id: null,
        shopsId: null,
        shopsCode: null,
        chargeItemName: null,
        chargeItemId: null,
        univalence: null,
        startTime: null,
        endTime: null,
        deadlineTime: null,
        lastData: null,
        thisData: null,
        rate: null,
        wastage: null,
        number: null,
        latefee: null,
        money: null,
        fundsReceived: null,
        paymentState: null,
        refundStatus: null,
        totalRefundAmount: null,
        billNumber: null,
        chargeTime: null,
        payId: null,
        chargeUser: null
      },
      // 表单校验
      rules: {
        shopsId: [
          {required: true, message: "商铺编号不能为空", trigger: "change"}
        ],
        chargeItemId: [
          {required: true, message: "收费id不能为空", trigger: "change"}
        ],
        univalence: [
          {required: true, message: "单价不能为空", trigger: "blur"}
        ],
        startTime: [
          {required: true, message: "费用开始时间不能为空", trigger: "blur"}
        ],
        endTime: [
          {required: true, message: "费用结束时间不能为空", trigger: "blur"}
        ],
        deadlineTime: [
          {required: true, message: "缴费期限不能为空", trigger: "blur"}
        ],
        number: [
          {required: true, message: "数量不能为空", trigger: "blur"}
        ],
        money: [
          {required: true, message: "金额不能为空", trigger: "blur"}
        ]
        // chargeTime: [
        //   { required: true, message: "缴费时间不能为空", trigger: "blur" }
        // ],
        // chargeUser: [
        //   { required: true, message: "收款人姓名不能为空", trigger: "blur" }
        // ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    next() {
      if (this.active++ > 1) this.active = 0;
      this.getListBycode();
    },
    getListBycode() {
      this.loading = true;
      listChargedataByCode(this.queryParams).then(response => {
        this.chargedataList = response.rows;
        // this.total = response.total;
        this.loading = false;
      });
      listShops().then(response => {
        this.shopsList = response.rows;
        console.log(this.shopsList);
      });
      listChargeitem().then(response => {
        this.chargeitemList = response.rows;
      });
      listPaymentmethod().then(response => {
        this.paymentmethodList = response.rows;
      });

    },
    /** 查询收费数据列表 */
    getList() {
      this.loading = true;
      listChargedata(this.queryParams).then(response => {
        this.chargedataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listShops().then(response => {
        this.shopsList = response.rows;
      });
      listChargeitem().then(response => {
        this.chargeitemList = response.rows;
      });
      listPaymentmethod().then(response => {
        this.paymentmethodList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open2 = false;
      this.form = {
        id: null,
        shopsId: null,
        shopsCode: null,
        chargeItemName: null,
        chargeItemId: null,
        univalence: null,
        startTime: null,
        endTime: null,
        deadlineTime: null,
        lastData: null,
        thisData: null,
        rate: null,
        wastage: null,
        number: null,
        latefee: null,
        money: null,
        fundsReceived: null,
        paymentState: null,
        refundStatus: null,
        totalRefundAmount: null,
        billNumber: null,
        chargeTime: null,
        payId: null,
        chargeUser: null
      };
      // this.form.univalence="123"
      this.reset();
      this.queryParams.chargeItemId = null;
    },
    // 表单重置
    reset() {

      this.resetForm("form");

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // this.reset();
      this.open = true;
      this.title = "添加收费数据";
    },
    handleAdds() {
      this.open2 = true;
      this.title = "批量添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      const id = row.id || this.ids
      getChargedata(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改收费数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log('==' + this.form.chargeItemId)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateChargedata(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.queryParams.chargeItemId = null;
              this.getList();
              console.log(this.chargedataList)
              console.log(this.chargeitemList)
            });
          } else {
            addChargedata(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.queryParams.chargeItemId = null;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除收费数据编号为"' + ids + '"的数据项？').then(function () {
        return delChargedata(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('zxwy/chargedata/export', {
        ...this.queryParams
      }, `chargedata_${new Date().getTime()}.xlsx`)
    },

    // 最终数量实时显示
    calculateLastNumber() {
      // 这里简单示例计算逻辑，实际可能更复杂，比如考虑损耗百分比等
      if (this.form.thisData !== '' && this.form.rate !== '' && this.form.wastage !== '' && this.form.lastData !==
        '') {
        // 最终数量 = (本期读数-上期读数)*倍率+损耗
        const calculatedLastNumber = (this.form.thisData - this.form.lastData) * parseFloat(this.form.rate) +
          parseFloat(this.form.wastage)
        this.form.number = calculatedLastNumber; // 四舍五入到两位小数，根据需求调整
      } else {
        this.form.number = ''; // 如果有任何一个值缺失，清空最终数量
      }
    },
    // 最终金额实时显示
    calculateLastMoney() {
      if (this.form.number !== '' && this.form.univalence !== '') {
        // 最终金额 = 单价*数量
        const calculateLastMoney = this.form.number * this.form.univalence
        this.form.money = calculateLastMoney; // 四舍五入到两位小数，根据需求调整
      } else {
        this.form.money = ''; // 如果有任何一个值缺失，清空最终数量
      }
    }
  },
  watch: {
    //监听上期读数
    'form.lastData'(newLastData) {
      this.calculateLastNumber();
    },
    //监听本期读数
    'form.thisData'(newThisData) {
      this.calculateLastNumber();
    },
    // 监听倍率变化
    'form.rate'(newRate) {
      this.calculateLastNumber();
    },
    // 监听损耗变化
    'form.wastage'(newWastage) {
      this.calculateLastNumber();
    },
    // 监听数量变化
    'form.number'(newNumber) {
      this.calculateLastMoney();
    },
    // 监听单价变化
    'form.univalence'(newUnivalence) {
      this.calculateLastMoney();
    }
  }
};
</script>
